<template>
  <div class="card resource-card">
    <div class="card-header">
      <div class="title">
        <Icon icon="ant-design:pie-chart-outlined" :size="16" />
        <span>{{ t('tb.baseInfo.sections.resources') }}</span>
      </div>
    </div>
    <div class="charts-grid">
      <div class="chart-item">
        <div ref="memoryRef" class="chart-container"></div>
        <div class="chart-label">{{ t('tb.baseInfo.resources.memory') }}</div>
      </div>
      <div class="chart-item chart-item--cpu">
        <div ref="cpuRef" class="chart-container"></div>
        <div class="chart-center">
          <span class="chart-center__label">{{ t('tb.baseInfo.resources.used') }}</span>
          <span class="chart-center__value">{{ cpuPercentText }}</span>
        </div>
        <div class="chart-label">{{ t('tb.baseInfo.resources.cpu') }}</div>
      </div>
      <div class="chart-item">
        <div ref="diskRef" class="chart-container"></div>
        <div class="chart-label">{{ t('tb.baseInfo.resources.disk') }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch, Ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useECharts } from '/@/hooks/web/useECharts';
  import { Icon } from '/@/components/Icon';
  import type { ResourceUsageMetrics, ResourceMetric } from '../types';

  const props = defineProps<{
    data: ResourceUsageMetrics;
  }>();

  const { t } = useI18n();
  const memoryRef = ref<HTMLDivElement | null>(null);
  const cpuRef = ref<HTMLDivElement | null>(null);
  const diskRef = ref<HTMLDivElement | null>(null);

  const { setOptions: setMemoryOptions } = useECharts(memoryRef as Ref<HTMLDivElement>);
  const { setOptions: setCpuOptions } = useECharts(cpuRef as Ref<HTMLDivElement>);
  const { setOptions: setDiskOptions } = useECharts(diskRef as Ref<HTMLDivElement>);

  watch(
    () => props.data,
    () => {
      updateCharts();
    },
    { deep: true },
  );

  onMounted(() => {
    updateCharts();
  });

  function clampMetric(metric: ResourceMetric) {
    const used = Math.max(metric.used ?? 0, 0);
    const total = Math.max(metric.total ?? 0, 0);
    const safeTotal = Math.max(total, used);
    return {
      used,
      total,
      safeTotal,
      availableDisplay: Math.max(total - used, 0),
      availableForChart: Math.max(safeTotal - used, 0),
    };
  }

  function buildPieSeries(metric: ResourceMetric, colors: { used: string; available: string }) {
    const labels = {
      used: t('tb.baseInfo.resources.used'),
      available: t('tb.baseInfo.resources.available'),
    };
    const normalized = clampMetric(metric);
    const hasData = normalized.safeTotal > 0;
    const chartUsed = hasData ? normalized.used : 0;
    const chartAvailable = hasData ? normalized.availableForChart : 1;
    const displayValues: Record<string, number> = {
      [labels.used]: normalized.used,
      [labels.available]: normalized.availableDisplay,
    };

    return {
      data: [
        { value: chartUsed, name: labels.used, itemStyle: { color: colors.used } },
        { value: chartAvailable, name: labels.available, itemStyle: { color: colors.available } },
      ],
      formatter: ({ name }: { name: string }) => {
        const value = displayValues[name] ?? 0;
        const unit = metric.unit || '';
        return `${name}\n${value}${unit}`;
      },
    };
  }

  const cpuPercentText = computed(() => {
    const percent = props.data?.cpu?.percent ?? 0;
    const normalized = Math.min(Math.max(Number(percent) || 0, 0), 100);
    return `${normalized}%`;
  });

  function updateCharts() {
    const { memory, cpu, disk } = props.data;

    const memorySeries = buildPieSeries(memory, { used: '#ef4444', available: '#22c55e' });

    // Memory Chart (Pie)
    setMemoryOptions({
      tooltip: { trigger: 'item' },
      series: [
        {
          type: 'pie',
          radius: '70%', // Filled pie
          avoidLabelOverlap: false,
          label: {
            show: true,
            position: 'outside',
            formatter: memorySeries.formatter,
            color: '#64748b',
          },
          labelLine: { show: true },
          data: memorySeries.data,
        },
      ],
    });

    // CPU Chart (Ring/Donut)
    const cpuUsed = Math.min(Math.max(cpu.percent ?? 0, 0), 100);
    const cpuAvailable = Math.max(100 - cpuUsed, 0);
    const availableColor = '#3b82f6';
    const usedColor = '#cbd5f5';
    const cpuData = [];
    const hasUsage = cpuUsed > 0;

    const availableValue = hasUsage ? cpuAvailable : 100;
    cpuData.push({
      value: availableValue,
      name: t('tb.baseInfo.resources.available'),
      itemStyle: { color: availableColor },
      label: { show: false },
    });

    if (hasUsage) {
      cpuData.push({
        value: cpuUsed,
        name: t('tb.baseInfo.resources.used'),
        itemStyle: { color: usedColor },
        label: { show: false },
      });
    }

    setCpuOptions({
      tooltip: { trigger: 'item' },
      series: [
        {
          type: 'pie',
          radius: ['60%', '80%'], // Ring
          avoidLabelOverlap: false,
          label: { show: false },
          labelLine: { show: false },
          data: cpuData,
        },
      ],
    });

    // Disk Chart (Pie)
    const diskSeries = buildPieSeries(disk, { used: '#ef4444', available: '#3b82f6' });
    setDiskOptions({
      tooltip: { trigger: 'item' },
      series: [
        {
          type: 'pie',
          radius: '70%', // Filled pie
          avoidLabelOverlap: false,
          label: {
            show: true,
            position: 'outside',
            formatter: diskSeries.formatter,
            color: '#64748b',
          },
          labelLine: { show: true },
          data: diskSeries.data,
        },
      ],
    });
  }
</script>

<style scoped lang="less">
  .card {
    background: #fff;
    border-radius: 16px;
    padding: 16px;
    box-shadow: 0 6px 20px rgba(15, 23, 42, 0.08);
  }
  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  }
  .title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #0f172a;
  }
  .charts-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
  }
  .chart-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
  }
  .chart-container {
    width: 100%;
    height: 180px;
  }
  .chart-label {
    margin-top: 8px;
    font-size: 13px;
    color: #64748b;
  }

  .chart-item--cpu .chart-center {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 30px; /* leave space for label */
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    pointer-events: none;
  }

  .chart-center__label {
    font-size: 12px;
    color: #94a3b8;
    line-height: 16px;
  }

  .chart-center__value {
    font-size: 20px;
    font-weight: 600;
    color: #0f172a;
    line-height: 24px;
  }
</style>
